<script lang="ts" setup>
import flowchart from 'flowchart.js'
import { watch, onMounted, ref } from 'vue'
import { convertToFlowChart } from '@/apis/index'
import { debounce } from '@/utils/common'
import { OptionType } from './flowChart.type'
import { useConfigStore } from '@/stores/useConfigStore'
import { EditorTheme } from '@/types/enum/configEnum'

const props = defineProps({
  code: {
    type: String,
    default: ''
  },
  id: {
    type: String,
    default: 'flowChart'
  },
  setWidth: {
    type: Boolean,
    default: true
  },
  optionMode: {
    type: Number,
    default: OptionType.Day
  },
  callback:{
    type: Function,
    default: () => {}
  }
})

const flowRef = ref<HTMLDivElement | null>(null)

// 格式化Python代码
const formatPythonCode = (code: string): string => {
  // 按照\n将code字符串进行拆分
  const lines = code.split('\n')
  // 遍历拆分后的数组，在每一行前添加四个空格
  const formattedLines = lines.map(line => '    ' + line)
  // 在数组前添加def main():
  const formattedCode = 'def start():\n' + formattedLines.join('\n')
  return formattedCode
}

// 获取dctCode
const getDstCode = async () => {
  return convertToFlowChart(formatPythonCode(props.code))
}

const drawFlowChart = (dstCode: string, config: any) => {
  console.log('drawFlowChart====>')
  try {
    if (flowRef.value) {
      flowRef.value.innerHTML = ''
      let diagram = flowchart.parse(dstCode)
      diagram.drawSVG(props.id, config)
    }
  } catch {
    console.log('error')
  }
}

// 控制加载状态
const loading = ref(true)

// 白天模式
const dayModeOptions = {
  // 'x': 30,
  // 'y': 50,
  'line-width': 3,
  // maxWidth: 3, //ensures the flowcharts fits within a certian width
  'line-length': 50,
  'text-margin': 10,
  'font-size': 14,
  font: 'normal',
  'font-family': 'Helvetica',
  'font-weight': 'normal',
  'font-color': 'black',
  'line-color': '#ddf3ff',
  'element-color': '#ddf3ff',
  fill: 'white',
  'yes-text': 'yes',
  'no-text': 'no',
  'arrow-end': 'block',
  scale: 1,
  symbols: {
    start: {
      'font-color': 'black',
      'element-color': '#ddf3ff',
      fill: '#ddf3ff'
    },
    end: {
      class: 'end-element'
    }
  },
  flowstate: {
    past: { fill: '#CCCCCC', 'font-size': 12 },
    current: { fill: '#ddf3ff', 'font-color': 'red', 'font-weight': 'bold' },
    future: { fill: '#ddf3ff' },
    request: { fill: '#ddf3ff' },
    invalid: { fill: '#ddf3ff' },
    approved: {
      fill: '#58C4A3',
      'font-size': 12,
      'yes-text': 'APPROVED',
      'no-text': 'n/a'
    },
    rejected: {
      fill: '#C45879',
      'font-size': 12,
      'yes-text': 'n/a',
      'no-text': 'REJECTED'
    }
  }
}

// 黑夜模式
const nightModeOptions = {
  // 'x': 30,
  // 'y': 50,
  'line-width': 3,
  // maxWidth: 3, //ensures the flowcharts fits within a certian width
  'line-length': 50,
  'text-margin': 10,
  'font-size': 14,
  font: 'normal',
  'font-family': 'Helvetica',
  'font-weight': 'normal',
  'font-color': 'white',
  'line-color': '#00bc7b',
  'element-color': '#00bc7b',
  fill: 'white',
  'yes-text': 'yes',
  'no-text': 'no',
  'arrow-end': 'block',
  scale: 1,
  symbols: {
    start: {
      'font-color': 'white',
      'element-color': '#00bc7b',
      fill: '#00bc7b'
    },
    end: {
      class: 'end-element'
    }
  },
  flowstate: {
    past: { fill: '#CCCCCC', 'font-size': 12 },
    current: { fill: '#00bc7b', 'font-color': 'red', 'font-weight': 'bold' },
    future: { fill: '#00bc7b' },
    request: { fill: '#00bc7b' },
    invalid: { fill: '#00bc7b' },
    approved: {
      fill: '#58C4A3',
      'font-size': 12,
      'yes-text': 'APPROVED',
      'no-text': 'n/a'
    },
    rejected: {
      fill: '#C45879',
      'font-size': 12,
      'yes-text': 'n/a',
      'no-text': 'REJECTED'
    }
  }
}

// 控制流程图的颜色
const configStore = useConfigStore()

const handleDrawFlowChart = () => {
  loading.value = true
  getDstCode()
    .then(res => {
      if (res.data.success) {
        const dstCode: string = res.data.result
        const option =
          configStore.getEditorConfig().theme === EditorTheme.dark
            ? OptionType.Night
            : OptionType.Day

        // 控制流程图的颜色
        drawFlowChart(dstCode, option === OptionType.Night ? nightModeOptions : dayModeOptions)
        const svg = document.querySelector(`#${props.id} svg`)
        if (svg && props.setWidth) {
          svg.setAttribute('width', '100%')
          svg.setAttribute('height', '100%')
        }
        // codeStatus.value = true
      } else {
        ElMessage.warning('代码有错误...')
        // codeStatus.value = false
        // tips.value = res.data.message
        console.log(res)
      }
      props.callback(res.data)
    })
    .catch(() => {
      ElMessage.warning('代码有错误...')
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  watch(() => props.code, debounce(handleDrawFlowChart, 1000))
})

defineExpose({
  handleDrawFlowChart
})

</script>

<template>
  <section class="flow-chart-container">
    <section style="position: relative; width: 100%; height: 100%">
      <loading-animation v-show="loading"></loading-animation>
      <div :id="props.id" ref="flowRef" v-show="!loading" class="my-flowChart"></div>
    </section>
  </section>
</template>

<style lang="scss" scoped>
.flow-chart-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: var(--flow-chart-bgc);
}
.mask {
  position: absolute;
  width: 15%;
  height: 15%;
}
.my-flowChart {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
